<?php
namespace oss;

require_once APP_PATH . '/../extend/aliyunoss/autoload.php';
use OSS\Core\OssException;
use OSS\OssClient;

class Oss
{

    private  $bucket;
    private  $ossClient;
    public  function __construct()
    {
        $accessKeyId = config('accessKeyId');
        $accessKeySecret = config('accessKeySecret');
        $endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        $this->bucket= "xuexiang";
        $this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    }

    /**
     * 获取阿里云对象存储路径
     * @param   $filePath    文件路径
     * @param   $fileType    文件类型
     * @return  url          文件链接
     */
    public static function getOssUrl($filePath, $fileType = 'png')
    {
        $accessKeyId = config('accessKeyId');
        $accessKeySecret = config('accessKeySecret');
        $endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        $bucket= "xuexiang";
        $object = time().'.'.$fileType;

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $result = $ossClient->uploadFile($bucket, $object, $filePath);

        return $result['info']['url'];
    }


    public  function updateOss($file,$name){
        try{
            $result = $this->ossClient->uploadFile($this->bucket, $name, $file);
        } catch(OssException $e) {
            return $e->getMessage();
        }
        return $result;
    }

    public function deleteOss($url){
        try{
            $arr = explode('/',$url);
            $name = $arr[count($arr)-1];
            $result = $this->ossClient->deleteObject($this->bucket,$name);
        } catch(OssException $e) {
            return $e->getMessage();
        }
        return $result;
    }




}